<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询班级名称" v-model="searchClassname"></el-input>
      <el-button type="primary" @click="loadClasses(1)">查询</el-button>
      <el-button type="info" @click="resetSearch">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
    </div>
    <el-table :data="classesData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }">
      <el-table-column prop="classid" label="班级ID" width="70" align="center"></el-table-column>
      <el-table-column prop="classname" label="班级名称"></el-table-column>
      <el-table-column prop="creatorid" label="创建者ID"></el-table-column>
      <el-table-column prop="name" label="创建者名字"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="班级信息" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="班级名称" prop="classname">
          <el-input v-model="form.classname" placeholder="班级名称"></el-input>
        </el-form-item>
        <el-form-item label="创建者ID" prop="creatorid">
          <el-input v-model="form.creatorid" placeholder="创建者ID"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Classes",
  data() {
    return {
      classesData: [],  // 所有的班级数据
      pageNum: 1,       // 当前的页码
      pageSize: 10,     // 每页显示的个数
      searchClassname: '',
      total: 0,
      dialogVisible: false,
      form: {},
      rules: {
        classname: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          { min: 1, max: 50, message: '班级名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        creatorid: [
          { required: true, message: '请输入创建者ID', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadClasses();
  },
  methods: {
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝
      this.dialogVisible = true;
    },
    handleAdd() {
      this.form = {}; // 清空表单
      this.dialogVisible = true;
    },
        // 获取上传者名字
    //TODO: 待优化
    async fetchName(uploaderId) {
      try {
        const res = await this.$request.get(`/users/selectNameById/${uploaderId}`);
        console.log('获取上传者名字', res.data); 
        return res.data;
      } catch (error) {
        console.error('获取上传者名字失败', error);
        return null;
      }
    },

    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const url = this.form.classid ? '/classes/update' : '/classes/add';
          const method = this.form.classid ? 'PUT' : 'POST';
          this.$request({
            url: url,
            method: method,
            data: this.form,
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.loadClasses(1);
              this.dialogVisible = false;
            } else {
              this.$message.error(res.msg);
            }
          }).catch(error => {
            console.error('Request failed:', error);
            this.$message.error('保存失败，请重试。');
          });
        }
      });
    },
    resetSearch() {
      this.searchClassname = '';
      this.loadClasses();
    },
    handleCurrentChange(pageNum) {
      this.loadClasses(pageNum);
    },
    async loadClasses(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      try {
        const res = await this.$request.get('/classes/selectByPage', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            classname: this.searchClassname
          }
        });
        this.classesData = res.data.records || [];
        this.total = res.data.total || 0;

    //获取创建者名字
    for (let i = 0; i < this.classesData.length; i++) {
      const creatorid = this.classesData[i].creatorid;
      const name = await this.fetchName(creatorid);
      this.$set(this.classesData[i], 'name', name);
    }
    

      } catch (error) {
        console.error('请求班级数据失败', error);
        this.classesData = [];
        this.total = 0;
        this.$message.error('加载班级数据失败');
      }
    },
  },
};
</script>

<style scoped>
/* Add your CSS styles here */
</style>